import 'package:flutter/material.dart';
import 'package:flutter_base/base/widget/base_get_builder.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/pages/chat/model/model_chat_base.dart';
import 'package:flutter_base/pages/chat/model/model_chat_too_short.dart';
import 'package:flutter_base/pages/chat/model/model_chat_clarification.dart';
import 'package:flutter_base/pages/chat/model/model_chat_test_created.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/widgets/appbar/common_app_bar.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_base/widgets/textfield/custom_text_field.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'digital_human_chat_logic.dart';

class DigitalHumanChatPage extends StatelessWidget {
  DigitalHumanChatPage({Key? key}) : super(key: key);

  final DigitalHumanChatLogic logic = Get.put(DigitalHumanChatLogic());

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<DigitalHumanChatLogic>(
      appBar: const CommonAppBar(
        title: '',
      ),
      backgroundColor: AppColor.colorF8F9FD,
      extendBodyBehindAppBar: true,
      builder: (controller) {
        return Stack(
          children: [
            // 背景图和数字人形象
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                  width: 375.w,
                  height: 240.w,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage(
                          Assets.homeTopBg,
                        ),
                        fit: BoxFit.cover),
                  ),
                  child: Align(
                    alignment: Alignment.bottomCenter,
                    child: AutoImage(
                      Assets.homeDigitalHuman,
                      width: 200.w,
                      height: 200.w,
                      fit: BoxFit.cover,
                    ),
                  )),
            ),

            // 聊天内容区域
            Positioned.fill(
                top: 224.w,
                child: Container(
                  decoration: BoxDecoration(
                      color: AppColor.colorF5F7FA,
                      borderRadius: BorderRadius.only(
                          topRight: Radius.circular(20.w),
                          topLeft: Radius.circular(20.w))),
                  child: Column(
                    children: [
                      // 消息列表

                      Expanded(
                        child: _buildMessageList(controller),
                      ),

                      // 底部输入区域
                      _buildInputArea(),
                    ],
                  ),
                )),
          ],
        );
      },
    );
  }

  // 构建消息列表
  Widget _buildMessageList(DigitalHumanChatLogic controller) {
    return ListView.builder(
      controller: controller.scrollController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.w),
      itemCount: controller.messages.length,
      itemBuilder: (context, index) {
        final message = controller.messages[index];
        return _buildMessageItem(message);
      },
    );
  }

  // 构建消息项
  Widget _buildMessageItem(ModelChatBase message) {
    return Padding(
      padding: EdgeInsets.only(bottom: 12.w),
      child: _buildMessageBubble(message),
    );
  }

  // 构建消息气泡
  Widget _buildMessageBubble(ModelChatBase message) {
    // 根据消息的stage类型决定样式
    final bool isUserMessage = message.stage == 'user';

    // 用户发送的消息，使用蓝色气泡，靠右对齐
    if (isUserMessage) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: 270.w),
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.w),
            decoration: BoxDecoration(
              color: AppColor.primary, // 使用主题色 #19DBF2
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.w),
                topRight: Radius.circular(2.w),
                bottomLeft: Radius.circular(20.w),
                bottomRight: Radius.circular(8.w),
              ),
            ),
            child: Text(
              message.message ?? '',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                fontFamily: 'Outfit',
              ),
            ),
          ),
        ],
      );
    }

    // 欢迎消息或机器人回复，使用白色气泡，靠左对齐
    else if (message.stage == 'hello' ||
        message.stage == 'inappropriate_content' ||
        message.stage == 'invalid_input' ||
        message.stage == 'vague_input' ||
        message.stage == 'input_too_short' ||
        message.stage == 'need_confirmation' ||
        message.stage == 'need_clarification' ||
        message.stage == 'test_created') {
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: 320.w),
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(2.w),
                topRight: Radius.circular(20.w),
                bottomLeft: Radius.circular(8.w),
                bottomRight: Radius.circular(20.w),
              ),
              border: Border.all(
                color: message.stage == 'test_created'
                    ? AppColor.primary
                    : Colors.transparent, // 边框使用主题色
                width: 1.w,
              ),
            ),
            child: _buildMessageContent(message),
          ),
        ],
      );
    }

    // 默认消息样式
    return Container(
      margin: EdgeInsets.only(bottom: 8.w),
      child: Text(
        message.message ?? '未知消息',
        style: TextStyle(
          color: AppColor.color0C0A09,
          fontSize: 14.sp,
        ),
      ),
    );
  }

  // 构建消息内容
  Widget _buildMessageContent(ModelChatBase message) {
    // 如果是输入太短的消息类型
    if (message.stage == 'input_too_short' ||
        message.stage == 'vague_input' ||
        message.stage == 'invalid_input' ||
        message.stage == 'inappropriate_content') {
      final tooShortMessage = message as ModelChatTooShort;

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 主要消息
          Text(
            message.message ?? '',
            style: TextStyle(
              color: AppColor.color0C0A09,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              fontFamily: 'Outfit',
            ),
          ),

          // 如果有建议和替代选项
          if (tooShortMessage.suggestion != null)
            Padding(
              padding: EdgeInsets.only(top: 8.w),
              child: Text(
                tooShortMessage.suggestion!,
                style: TextStyle(
                  color: AppColor.color0C0A09,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  fontFamily: 'Outfit',
                ),
              ),
            ),

          // 替代问题选项列表
          if (tooShortMessage.alternatives != null &&
              tooShortMessage.alternatives!.isNotEmpty)
            Padding(
              padding: EdgeInsets.only(top: 8.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: tooShortMessage.alternatives!.map((alternative) {
                  return GestureDetector(
                    onTap: () {
                      logic.sendMessage(message: alternative);
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 8.w),
                      child: Text(
                        '"${alternative ?? ''}"',
                        style: TextStyle(
                          color: AppColor.hex("1875F9"), // 蓝色文本
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                          fontFamily: 'Outfit',
                        ),
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
        ],
      );
    }

    // 测试创建类型消息
    else if (message.stage == 'test_created') {
      final testCreatedMessage = message as ModelChatTestCreated;
      return _buildTestCreatedContent(testCreatedMessage);
    }

    // 需要澄清的问题类型
    else if (message.stage == 'need_clarification') {
      final clarificationMessage = message as ModelChatClarification;

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 主要消息
          Text(
            message.message ?? '',
            style: TextStyle(
              color: AppColor.color0C0A09,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              fontFamily: 'Outfit',
            ),
          ),

          // 原始问题
          if (clarificationMessage.originalQuestion != null)
            Padding(
              padding: EdgeInsets.only(top: 8.w, bottom: 16.w),
              child: RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: '您的问题: ',
                      style: TextStyle(
                        color: AppColor.color7F909E,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w400,
                        fontFamily: 'Outfit',
                      ),
                    ),
                    TextSpan(
                      text: '"${clarificationMessage.originalQuestion}"',
                      style: TextStyle(
                        color: AppColor.color0C0A09,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        fontStyle: FontStyle.italic,
                        fontFamily: 'Outfit',
                      ),
                    ),
                  ],
                ),
              ),
            ),

          // 显示历史问题和回答
          _buildAnsweredQuestions(clarificationMessage),

          // 显示当前需要回答的问题
          if (clarificationMessage.clarifyQuestions != null &&
              clarificationMessage.clarifyQuestions!.isNotEmpty)
            _buildClarifyQuestion(clarificationMessage),
        ],
      );
    }

    // 默认直接显示消息文本
    return Text(
      message.message ?? '',
      style: TextStyle(
        color: AppColor.color0C0A09,
        fontSize: 14.sp,
        fontWeight: FontWeight.w500,
        fontFamily: 'Outfit',
      ),
    );
  }

  // 构建测试创建内容
  Widget _buildTestCreatedContent(ModelChatTestCreated testCreatedMessage) {
    final testInfo = testCreatedMessage.testInfo;
    if (testInfo == null) {
      return Text(
        testCreatedMessage.message ?? '测试已创建',
        style: TextStyle(
          color: AppColor.color0C0A09,
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
          fontFamily: 'Outfit',
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 头部信息：图标+测试名称
        Padding(
          padding: EdgeInsets.all(12.w),
          child: Row(
            children: [
              // 测试图标
              Container(
                width: 36.w,
                height: 36.w,
                decoration: BoxDecoration(
                  color: const Color(0xFFDDF9FF), // 浅蓝色背景
                  borderRadius: BorderRadius.circular(40.w),
                ),
                child: testInfo.image != null && testInfo.image!.isNotEmpty
                    ? ClipRRect(
                        borderRadius: BorderRadius.circular(40.w),
                        child: ImageView(
                          imageUrl:
                              "http://192.168.5.201:9000/echomindcdn/${testInfo.image}",
                          width: 36.w,
                          height: 36.w,
                          fit: BoxFit.cover,
                        ),
                      )
                    : Center(
                        child: Icon(
                          Icons.psychology,
                          color: AppColor.primary,
                          size: 20.w,
                        ),
                      ),
              ),

              SizedBox(width: 6.w),

              // 测试名称
              Expanded(
                child: Text(
                  testInfo.name ?? '心理测试',
                  style: TextStyle(
                    color: AppColor.color0C0A09,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    fontFamily: 'Outfit',
                  ),
                ),
              ),
            ],
          ),
        ),

        // 测试详细信息
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 测试标题
              Row(
                children: [
                  Expanded(child: Text(
                    testInfo.name ?? '心理测试',
                    style: TextStyle(
                      color: AppColor.color0C0A09,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w700,
                      fontFamily: 'Outfit',
                    ),
                  )),
                  12.horizontalSpace,
                  GestureDetector(
                    onTap: () {
                      // 处理开始测试按钮点击
                      if (testInfo.id != null) {
                        // 跳转到测试页面，需要根据实际情况调整路由
                        Get.toNamed('/test/detail',
                            arguments: {'testId': testInfo.id});
                      }
                    },
                    child: Container(
                      padding:
                      EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
                      decoration: BoxDecoration(
                        color: AppColor.primary,
                        borderRadius: BorderRadius.circular(78.w),
                      ),
                      child: Text(
                        "开始测试",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          fontFamily: 'Outfit',
                        ),
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 4.w),

              // 测试描述
              Text(
                testInfo.desc ?? '',
                style: TextStyle(
                  color: AppColor.color0C0A09.withOpacity(0.6),
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w400,
                  fontFamily: 'Outfit',
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),

        // 底部信息：题目数量、时间等
        Padding(
          padding: EdgeInsets.all(12.w),
          child: Row(
            children: [
              // 题目数量
              Text(
                "共${testInfo.questionCount}题",
                style: TextStyle(
                  color: AppColor.color7F909E,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w500,
                  fontFamily: 'Outfit',
                ),
              ),

              SizedBox(width: 32.w),

              // 测试时间
              if (testInfo.answerTime != null)
                Text(
                  "约需${testInfo.answerTime! ~/ 60}分钟",
                  style: TextStyle(
                    color: AppColor.color7F909E,
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w500,
                    fontFamily: 'Outfit',
                  ),
                ),

              // const Spacer(),

              // 开始测试按钮

            ],
          ),
        ),
      ],
    );
  }

  // 构建已回答的问题和答案
  Widget _buildAnsweredQuestions(ModelChatClarification clarificationMessage) {
    final sessionId = clarificationMessage.sessionId ?? '';
    final currentQuestionIndex = logic.getCurrentQuestionIndex(sessionId);

    // 如果还没有回答任何问题，则不显示
    if (currentQuestionIndex <= 0) {
      return const SizedBox.shrink();
    }

    // 获取已回答的问题和答案
    final answeredQuestions = <Widget>[];
    final answers = logic.getAnswers(sessionId);

    for (int i = 0;
        i < currentQuestionIndex &&
            i < clarificationMessage.clarifyQuestions!.length;
        i++) {
      final question = clarificationMessage.clarifyQuestions![i];
      final answer = answers[question?.id ?? ''];

      if (answer != null) {
        answeredQuestions.add(
          Padding(
            padding: EdgeInsets.only(bottom: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 问题文本
                Text(
                  question?.question ?? '',
                  style: TextStyle(
                    color: AppColor.color0C0A09,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily: 'Outfit',
                  ),
                ),

                SizedBox(height: 8.w),

                // 回答文本
                Container(
                  padding:
                      EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
                  decoration: BoxDecoration(
                    color: AppColor.primary.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8.w),
                  ),
                  child: Text(
                    answer,
                    style: TextStyle(
                      color: AppColor.color0C0A09,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Outfit',
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: answeredQuestions,
    );
  }

  // 构建澄清问题
  Widget _buildClarifyQuestion(ModelChatClarification clarificationMessage) {
    // 获取当前待回答的问题索引
    int currentQuestionIndex =
        logic.getCurrentQuestionIndex(clarificationMessage.sessionId ?? '');

    // 如果所有问题都已回答，则不显示任何问题
    if (currentQuestionIndex >=
        (clarificationMessage.clarifyQuestions?.length ?? 0)) {
      return const SizedBox.shrink();
    }

    // 获取当前问题
    final currentQuestion =
        clarificationMessage.clarifyQuestions![currentQuestionIndex];

    // 设置当前活动问题信息，以便底部输入框可以正确提交答案
    // logic.setActiveQuestion(
    //   sessionId: clarificationMessage.sessionId ?? '',
    //   questionId: currentQuestion?.id ?? '',
    //   detectedTypeId: clarificationMessage.detectedTypeId,
    // );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 问题文本
        Text(
          currentQuestion?.question ?? '',
          style: TextStyle(
            color: AppColor.color0C0A09,
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
            fontFamily: 'Outfit',
          ),
        ),

        SizedBox(height: 12.w),

        // 只有select类型的问题显示选项，text类型使用底部输入框
        if (currentQuestion?.type == 'select')
          _buildSelectOptions(
            options: currentQuestion?.options ?? [],
            questionId: currentQuestion?.id ?? '',
            sessionId: clarificationMessage.sessionId ?? '',
            detectedTypeId: clarificationMessage.detectedTypeId,
          )
        else
          // 文本类型提示
          Padding(
            padding: EdgeInsets.only(bottom: 8.w),
            child: Text(
              '请在底部输入框中输入您的回答',
              style: TextStyle(
                color: AppColor.color7F909E,
                fontSize: 14.sp,
                fontStyle: FontStyle.italic,
              ),
            ),
          ),
      ],
    );
  }

  // 构建选择选项
  Widget _buildSelectOptions({
    List<String>? options,
    required String questionId,
    required String sessionId,
    int? detectedTypeId,
  }) {
    if (options == null || options.isEmpty) {
      return const SizedBox.shrink();
    }

    return Wrap(
      spacing: 8.w,
      runSpacing: 8.w,
      children: options.map((option) {
        return GestureDetector(
          onTap: () {
            // 提交选择的答案
            logic.submitAnswer(
              sessionId: sessionId,
              questionId: questionId,
              answer: option,
              detectedTypeId: detectedTypeId,
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20.w),
              border: Border.all(color: AppColor.colorE4EBF0),
            ),
            child: Text(
              option,
              style: TextStyle(
                color: AppColor.color0C0A09,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
      }).toList(),
    );
  }

  // 构建底部输入区域
  Widget _buildInputArea() {
    // 发送按钮组件
    final sendButton = Obx(() => GestureDetector(
          onTap: logic.showSendButton.value
              ? () {
                  // 判断是否有活动问题，如果有则作为回答提交
                  if (logic.hasActiveQuestion) {
                    logic.submitTextAnswer(logic.inputController.text.trim());
                  } else {
                    logic.sendMessage();
                  }
                }
              : null,
          child: Container(
            width: 36.w,
            height: 36.w,
            decoration: BoxDecoration(
              color: logic.showSendButton.value
                  ? AppColor.primary
                  : AppColor.colorF8F9FD,
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.send,
              color: logic.showSendButton.value
                  ? Colors.white
                  : AppColor.color7F909E,
              size: 16.w,
            ),
          ),
        ));

    return Container(
      color: Colors.white,
      child: SafeArea(
        top: false,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
          child: CustomTextField(
            textEditingController: logic.inputController,
            hintText: logic.hasActiveQuestion ? '请输入您对问题的回答...' : '请输入您的问题...',
            backgroundColor: AppColor.colorF8F9FD,
            right: sendButton,
            onSubmitted: (_) => logic.hasActiveQuestion
                ? logic.submitTextAnswer(logic.inputController.text.trim())
                : logic.sendMessage(),
            textInputAction: TextInputAction.send,
          ),
        ),
      ),
    );
  }
}
